package br.com.localfloripa.scheduling;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import br.com.localfloripa.dao.EnderecoDao;
import br.com.localfloripa.entities.Endereco;
import br.com.localfloripa.services.GeoCodingService;

@Component("geoCodeWorker")
public class GeoCodeWorker implements Worker {
	
	public static final Logger log = LoggerFactory.getLogger(GeoCodeWorker.class);
	public static Integer pageSize = 100;
	
	@Inject
	@Named("geoCodingService")
	private GeoCodingService geoService;
	
	@Inject
	@Named("enderecoDao")
	private EnderecoDao enderecoDao;

	@Async
	@Override
	public void periodicalWork() throws Exception {
		
	}

	@Async
	@Override
	public void dailyWork() throws Exception {
		log.info("GEOCODING SERVICE- "+Calendar.getInstance().getTime());
		
		try {
			short pageCount = 1;
			double total = enderecoDao.countEnderecos();
			double pages =  Math.ceil(total/pageSize);
			
			while (pageCount <= pages) {			
				List<Endereco> enderecos = enderecoDao.listEnderecoPaged(pageCount, pageSize);
				for (Endereco endereco: enderecos) {
					Map<String, BigDecimal> localizacao = geoService.geocode(endereco);
					if (localizacao.containsKey("lat") && localizacao.containsKey("long")) {
						endereco.setLatitude(localizacao.get("lat").doubleValue());
						endereco.setLongitude(localizacao.get("long").doubleValue());
						enderecoDao.merge(endereco);
					}									
				}			
				pageCount++;
			}
		} catch (Exception e) {
			ResourceBundle resource = ResourceBundle.getBundle("messages.MessageResources");
			log.error(resource.getString("scheduling.geocode.message.error"),e);
		}
	}

	@Override
	public void weeklyWork() throws Exception {
		// TODO Auto-generated method stub

	}

}
